<template>
  <KView class="sys-calendar">
    <KView class="sys-calendar-row">
      <KView>日</KView>
      <KView>一</KView>
      <KView>二</KView>
      <KView>三</KView>
      <KView>四</KView>
      <KView>五</KView>
      <KView>六</KView>
    </KView>
    <KView :key="yearMonth">
      <KView v-for="(weekList,rowIndex) in calendarList" :key="`week_${rowIndex}`" class="sys-calendar-row">
        <KView v-for="day in weekList" :key="day.text" :class="getDateClassName(day)">
          <slot name="day" :day="day">
            <span>{{$moment(day.text).date()}}</span>
          </slot>
        </KView>
      </KView>
    </KView>
  </KView>
</template>

<script>
  export default {
    props: {
      yearMonth: {
        type: [Number, String],
        required: true
      }
    },

    data() {
      return {
        calendarList: this.getCalendarList()
      };
    },

    methods: {
      getCalendarList() {
        let yearMonth = this.yearMonth;
        if (typeof yearMonth === 'string') {
          yearMonth = this.$moment(yearMonth, 'YYYY-MM').valueOf();
        }

        let startMoment = this.$moment(yearMonth).startOf('month');
        if (startMoment.isoWeekday() !== 7) {
          startMoment.isoWeekday(0);
        }

        let endMoment = this.$moment(yearMonth).endOf('month');
        if (endMoment.isoWeekday() < 7) {
          endMoment.isoWeekday(6);
        } else {
          endMoment.isoWeekday(13);
        }

        let calendarList = [];
        while (startMoment.isSameOrBefore(endMoment, 'day')) {
          let weekList = [];
          for (let i = 0; i < 7; i++) {
            weekList.push({
              text: startMoment.format('YYYY-MM-DD'),
              isSameMonth: this.$moment().isSame(startMoment, 'month')
            });
            startMoment.add(1, 'day');
          }
          calendarList.push(weekList);
        }
        return calendarList;
      },

      getDateClassName(day) {
        if (!day.isSameMonth) {
          return 'diff_month';
        }

        return '';
      }
    }
  };

</script>

<style lang="scss">
  .sys-calendar {
    .sys-calendar-row {
      height: formatPx(50);
      display: flex;
      flex-direction: row;
      margin-bottom: formatPx(24);

      &:last-child {
        margin-bottom: 0;
      }

      >div {
        flex: 1;
        line-height: formatPx(50);
        font-size: formatPx(28);
        text-align: center;
        color: #000000;

        &.diff_month {
          color: #999999;
        }
      }
    }
  }

</style>
